from cProfile import label
from datetime import datetime
from rest_framework import serializers
from rest_framework.exceptions import ValidationError

from apps.master.models import SerialNumberModel, DepartmentsModel
from apps.projectbases.models import ProjectPlanHModel, VersionHistoryModel, ProjectInfoModel, ProjectCustomerModel, \
    CommonSectionModel, CommonSectionTypeModel
from bases.apifields import ApiDecimalField
from bases.serializers import APIModelSerializer
from django.db import transaction
from django.utils import translation
from rest_framework.fields import empty
from apps.codetable.handles import field_codetable


class ProjectPlanHSerializer(APIModelSerializer):
    def __init__(self, instance=None, data=empty, **kwargs):
        super().__init__(instance, data, **kwargs)
        language = translation.get_language()
        self.status_dict = field_codetable('project_status', localization=language, model='Project')

    serialNumberFK = serializers.PrimaryKeyRelatedField(label='制番', queryset=SerialNumberModel.objects.all(), allow_null=True, required=False)
    serial_number = serializers.ReadOnlyField(source='serialNumberFK.serial_number')
    departmentFK = serializers.PrimaryKeyRelatedField(label='部门', queryset=DepartmentsModel.objects.all(), allow_null=True, required=False)
    department_name = serializers.ReadOnlyField(source='departmentFK.name')
    standard_curr = serializers.CharField(label='标准币种', max_length=3, allow_null=True, required=False)
    project_name = serializers.CharField(label='项目名称', max_length=50, allow_blank=True, allow_null=True, required=False)
    start_date = serializers.DateField(label='开始时间', allow_null=True, required=False)
    end_date = serializers.DateField(label='结束时间', allow_null=True, required=False)
    project_status = serializers.CharField(label='项目状态', max_length=1, allow_blank=True, allow_null=True, required=False)
    project_status_desc = serializers.SerializerMethodField()


    class Meta:
        model = ProjectPlanHModel
        fields = '__all__'

    def get_project_status_desc(self, obj):
        return self.status_dict.get(obj.project_status) if self.status_dict else obj.project_status

    def validate(self, attrs):
        start_date = attrs.get('start_date')
        end_date = attrs.get('end_date')
        serialNumberFK = attrs.get('serialNumberFK')

        query = ProjectPlanHModel.objects.filter(serialNumberFK__exact=serialNumberFK).order_by('-id').first()
        if query:
            if start_date <= query.end_date:
                self.handle_validation('start_date', '开始日期必须大于上一期的结束日期')

        if end_date < start_date:
            self.handle_validation('end_date', '结束日期必须大于开始日期')

        if self.request.method.lower() == 'post':
            if ProjectPlanHModel.objects.filter(serialNumberFK__exact=serialNumberFK, start_date__exact=start_date,
                                                end_date__exact=end_date).exists():
                raise ValidationError("制番+开始日期+结束日期的组合在系统中已经存在")
        else:
            if ProjectPlanHModel.objects.exclude(pk=self.instance.pk).filter(serialNumberFK__exact=serialNumberFK, start_date__exact=start_date,
                                                end_date__exact=end_date).exists():
                raise ValidationError("制番+开始日期+结束日期的组合在系统中已经存在")

        return super().validate(attrs)

    @transaction.atomic
    def create(self, validated_data):
        current_datetime = datetime.now()
        validated_data['project_status'] = 'O'
        project_plan_instance = super().create(validated_data)
        data = {
            'projectPlanFK': project_plan_instance,
            'version': 1,
            'version_date': current_datetime,
            'note': None,
            'created_id': self.request.user.id,
            'created_date': current_datetime
        }
        VersionHistoryModel.objects.create(**data)
        return project_plan_instance


class VersionHistorySerializer(APIModelSerializer):
    projectPlanFK = serializers.PrimaryKeyRelatedField(label='项目计划ID', queryset=ProjectPlanHModel.objects.all(), allow_null=True, required=False)
    version = serializers.IntegerField(label='版本号', allow_null=True, required=False)
    version_date = serializers.DateField(label='版本记录时间', allow_null=True, required=False)
    note = serializers.CharField(label='版本改动内容', max_length=150, allow_blank=True, allow_null=True, required=False)

    class Meta:
        model = VersionHistoryModel
        fields = '__all__'


class ProjectInfoSerializer(APIModelSerializer):
    projectPlanFK = serializers.PrimaryKeyRelatedField(label='项目计划ID', queryset=ProjectPlanHModel.objects.all(), allow_null=True, required=False)
    project_type = serializers.CharField(label='项目类别', max_length=10, allow_blank=True, allow_null=True, required=False)
    scope = serializers.CharField(label='软件包范围版本', max_length=100, allow_blank=True, allow_null=True, required=False)
    obj_product = serializers.CharField(label='对象制品', max_length=100, allow_blank=True, allow_null=True, required=False)
    internal_target = serializers.CharField(label='项目内部目标', max_length=255, allow_blank=True, allow_null=True, required=False)
    customer_target = serializers.CharField(label='客户项目目标', max_length=255, allow_blank=True, allow_null=True, required=False)
    responsibility = serializers.CharField(label='职责范围', max_length=200, allow_blank=True, allow_null=True, required=False)
    partner_company = serializers.CharField(label='合作公司', max_length=100, allow_blank=True, allow_null=True, required=False)

    class Meta:
        model = ProjectInfoModel
        fields = '__all__'



class ProjectCustomerSerializer(APIModelSerializer):
    projectPlanFK = serializers.PrimaryKeyRelatedField(label='项目计划ID', queryset=ProjectPlanHModel.objects.all(), allow_null=True, required=False)
    customer_code = serializers.CharField(label='客户代码', max_length=12, allow_blank=True, allow_null=True, required=False)
    customer_name = serializers.CharField(label='客户名称', max_length=50, allow_blank=True, allow_null=True, required=False)
    customer_url = serializers.CharField(label='客户URL', max_length=50, allow_blank=True, allow_null=True, required=False)
    sales_amount = ApiDecimalField(label='销售金额', max_digits=18, decimal_places=2, allow_null=True, required=False)
    customer_product = serializers.CharField(label='主要产品', max_length=50, allow_blank=True, allow_null=True, required=False)
    product_form = serializers.CharField(label='生产形态', max_length=50, allow_blank=True, allow_null=True, required=False)
    factory_num = serializers.IntegerField(label='据点工厂数',  allow_null=True, required=False)
    stock_clusters_num = serializers.IntegerField(label='据点在库集群数', allow_null=True, required=False)
    address = serializers.CharField(label='据点所在地', max_length=50, allow_blank=True, allow_null=True, required=False)
    product_num = serializers.IntegerField(label='产品数', allow_null=True, required=False)
    item_num = serializers.IntegerField(label='品目总数', allow_null=True, required=False)


    class Meta:
        model = ProjectCustomerModel
        fields = '__all__'

    def validate(self, attrs):
        sales_amount = attrs.get('sales_amount')
        if sales_amount <= 0:
            self.handle_validation('sales_amount', '不允许小于等于0')
        return super().validate(attrs)

class CommonSectionTypeSerializer(APIModelSerializer):
    section = serializers.CharField(label='类型', max_length=10, allow_blank=True, allow_null=True, required=False)
    section_item = serializers.CharField(label='类别', max_length=30, allow_blank=True, allow_null=True, required=False)

    class Meta:
        model = CommonSectionTypeModel
        unique_together = ('section', 'section_item')
        fields = '__all__'

    def validate(self, attrs):
        section = attrs.get('section')
        section_item = attrs.get('section_item')

        if self.request.method.lower() == 'post':
            if CommonSectionTypeModel.objects.filter(section__exact=section, section_item__exact=section_item).exists():
                raise ValidationError("类型+类别的组合在系统中已经存在")
        else:
            if CommonSectionTypeModel.objects.exclude(pk=self.instance.pk).filter(section__exact=section, section_item__exact=section_item).exists():
                raise ValidationError("类型+类别的组合在系统中已经存在")


class CommonSectionSerializer(APIModelSerializer):
    projectPlanFK = serializers.PrimaryKeyRelatedField(label='项目计划ID', queryset=ProjectPlanHModel.objects.all(),
                                                       allow_null=True, required=False)
    section = serializers.CharField(source='sectionFK.section')
    section_item = serializers.CharField(source='sectionFK.section_item')
    # section = serializers.SerializerMethodField()
    sectionFK = serializers.PrimaryKeyRelatedField(label='辅助信息类型ID',queryset=CommonSectionTypeModel.objects.all(),
                                                   allow_null=True, required=False)
    value = serializers.CharField(label='值', max_length=50, allow_blank=True, allow_null=True, required=False)

    class Meta:
        model = CommonSectionModel
        unique_together = ('projectPlanFK', 'sectionFK')
        fields = '__all__'

    # def get_section(self, obj):
    #     return obj['sectionFK__section']

